<template>
  <div class="app-container">
    <el-form :model="businessForm" ref="businessForm" :rules="rules" size="small" :inline="true" label-width="110px"
             label-position="right">
      <el-form-item label="合同价款" prop="leasingPrice" :rules="rules.leasingPrice"
      v-if="shouldDisplay('leasingPrice')">
        <el-input v-model="businessForm.leasingPrice" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">元</i>
        </el-input>
      </el-form-item>
      <el-form-item label="融资期限(月)" prop="leaseTermMonths" :rules="rules.leaseTermMonths"
      v-if="shouldDisplay('leaseTermMonths')">
        <el-input v-model="businessForm.leaseTermMonths" clearable style="width: 130px" placeholder="请输入">
        </el-input>
      </el-form-item>
      <el-form-item label="还款周期" prop="repaymentCycle" :rules="rules.repaymentCycle"
      v-if="shouldDisplay('repaymentCycle')">
        <el-select v-model="businessForm.repaymentCycle" style="width: 130px" @change="handleRepaymentCycleChange">
          <el-option v-for="item in repaymentCycleOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="宽限期" prop="gracePeriodMonths"
      v-if="shouldDisplay('gracePeriodMonths')">
        <el-tooltip class="item" effect="dark"
                    content="还款周期为月付/双月付/季付/半年付时，宽限期一期分别表示1个月/2个月/3个月/6个月"
                    placement="top">
          <el-input v-model="businessForm.gracePeriodMonths" clearable style="width: 130px" placeholder="请输入">
            <i slot="suffix">期</i>
          </el-input>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="起始日" prop="startDay" :rules="rules.startDay"
      v-if="shouldDisplay('startDay')">
        <el-date-picker v-model="businessForm.startDay" type="date" placeholder="选择日期" style="width: 130px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="停歇期" prop="breakPeriod"
      v-if="shouldDisplay('breakPeriod')">
        <el-select v-model="businessForm.breakPeriod" style="width: 130px" multiple collapse-tags :multiple-limit="5"
                   :disabled="businessForm.repaymentCycle !== 'MONTHLY'">
          <el-option v-for="item in breakPeriodOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="还款方式" prop="repaymentMethod" :rules="rules.repaymentMethod"
      v-if="shouldDisplay('repaymentMethod')">
        <el-select v-model="businessForm.repaymentMethod" style="width: 130px" :disabled="type === 'reverse'">
          <el-option v-for="item in repaymentMethodOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!--                <el-input v-model="businessForm.repaymentMethod" clearable style="width: 130px" placeholder="请输入" v-if="type === 'reverse'" :disabled="true">-->
        <!--                </el-input>-->
      </el-form-item>
      <el-form-item label="名义收益率" prop="nominalInterestRate" :rules="rules.nominalInterestRate"
      v-if="shouldDisplay('nominalInterestRate')">
        <el-input v-model="businessForm.nominalInterestRate" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item label="保证金抵扣方式" prop="marginDeductionMethod"
      v-if="shouldDisplay('marginDeductionMethod')">
        <el-select v-model="businessForm.marginDeductionMethod" style="width: 130px" :disabled="true">
          <el-option v-for="item in marginDeductionMethodOptions" :key="item.value" :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="还租时点" prop="rentPaymentTiming" :rules="rules.rentPaymentTiming"
      v-if="shouldDisplay('rentPaymentTiming')">
        <el-select v-model="businessForm.rentPaymentTiming" style="width: 130px">
          <el-option v-for="item in rentPaymentTimingOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="手续费税率" prop="feeTaxRate"
      v-if="shouldDisplay('feeTaxRate')">
        <el-select v-model="businessForm.feeTaxRate" style="width: 130px">
          <el-option v-for="item in feeTaxRateOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="租赁方式" prop="leasingMethod"
      v-if="shouldDisplay('leasingMethod')">
        <el-select v-model="businessForm.leasingMethod" style="width: 130px" :disabled="true">
          <el-option v-for="item in leasingMethodOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="首付款" prop="downPayment"
      v-if="type === 'front' && shouldDisplay('downPayment')">
        <!-- <div style="display:flex"> -->
          <el-input v-model="businessForm.downPayment" clearable style="width: 110px" placeholder="请输入">
            <i slot="suffix">元</i>
          </el-input>
          <!-- <img src="@/assets/images/lightning.svg" style="width: 20px;height: 32px;margin-left: 6px;" @click="ratioCalculatorFn('SFK')" alt="light"> -->
          <el-tooltip class="item" effect="dark" content="比例计算" placement="top">
            <i class="el-icon-s-operation" style="margin-left: 6px;" @click="ratioCalculatorFn('SFK')"></i>
          </el-tooltip>
        <!-- </div> -->
      </el-form-item>
      <el-form-item label="首付款比例" prop="downPaymentPercentage"
      v-if="type === 'front' && shouldDisplay('downPaymentPercentage')">
        <el-input v-model="downPaymentPercentage" clearable style="width: 130px" :disabled="true">
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item label="保证金" prop="margin"
      v-if="shouldDisplay('margin')">
        <!-- <div style="display:flex"> -->
          <el-input v-model="businessForm.margin" clearable style="width: 110px" placeholder="请输入">
            <i slot="suffix">元</i>
          </el-input>
          <!-- <img src="@/assets/images/lightning.svg" style="width: 20px;height: 32px;margin-left: 6px;" @click="ratioCalculatorFn('BZJ')" alt="light"> -->
          <el-tooltip class="item" effect="dark" content="比例计算" placement="top">
            <i class="el-icon-s-operation" style="margin-left: 6px;" @click="ratioCalculatorFn('BZJ')"></i>
          </el-tooltip>
        <!-- </div> -->
      </el-form-item>
      <el-form-item label="保证金比例" prop="marginPercentage"
      v-if="shouldDisplay('marginPercentage')">
        <el-input v-model="marginPercentage" clearable style="width: 130px" :disabled="true">
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item label="手续费" prop="fees"
      v-if="shouldDisplay('fees')">
        <el-input v-model="businessForm.fees" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">元</i>
        </el-input>
      </el-form-item>
      <el-form-item label="手续费率(年)" prop="feeRatePerYear"
      v-if="shouldDisplay('feeRatePerYear')">
        <el-input v-model="feeRatePerYear" clearable style="width: 130px" :disabled="true">
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item label="资金成本率" prop="capitalCostRate"
      v-if="shouldDisplay('capitalCostRate')">
        <el-input v-model="businessForm.capitalCostRate" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">%</i>
        </el-input>
      </el-form-item>
      <el-form-item label="出租人其他成本" prop="lessorOtherCosts"
      v-if="shouldDisplay('lessorOtherCosts')">
        <el-input v-model="businessForm.lessorOtherCosts" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">元</i>
        </el-input>
      </el-form-item>
      <el-form-item label="其他收入(含税)" prop="otherIncomeTaxIncluded"
      v-if="shouldDisplay('otherIncomeTaxIncluded')">
        <el-input v-model="businessForm.otherIncomeTaxIncluded" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">元</i>
        </el-input>
      </el-form-item>
      <el-form-item label="每月支付" prop="monthlyPayment" :rules="rules.monthlyPayment"
      v-if="type === 'reverse' && shouldDisplay('monthlyPayment')">
        <el-input v-model="businessForm.monthlyPayment" clearable style="width: 130px" placeholder="请输入">
          <i slot="suffix">元</i>
        </el-input>
      </el-form-item>
    </el-form>
    <el-row class="mb8" style="display: flex; justify-content: flex-end; margin-right: 10px;">
      <el-button type="primary" icon="el-icon-edit-outline" size="mini" @click="handleCount" :disabled="false">计算</el-button>
      <el-button type="primary" icon="el-icon-delete" size="mini" plain @click="handleClear" :disabled="false">清空</el-button>
      <el-button type="success" icon="el-icon-download" size="mini" plain @click="handleConfirmDownload" :disabled="false">下载</el-button>
    </el-row>

    <div v-if="type === 'reverse'">
      <el-divider></el-divider>
      <div style="font-weight: bold;margin-bottom: 10px;">计算后的首付款:{{ revenueCalculation.downPayment }}</div>
      <div style="font-weight: bold;margin-bottom: 10px;">
        计算后的首付款比例:{{ revenueCalculation.downPaymentPercentage }}%
      </div>
    </div>


    <el-divider></el-divider>
    <div style="font-weight: bold;margin-bottom: 10px;">项目收益测算</div>
    <el-row>
      <el-col :span="2">
        <div style="margin-top: 10px;">本息数据</div>
        <div style="margin-top: 20px;"
          v-if="shouldDisplay('税前收益')">
          税前收益</div>
        <div style="margin-top: 20px;"
          v-if="shouldDisplay('税后收益')">
          税后收益</div>
      </el-col>
      <el-col :span="22">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="租赁本金合计">{{ revenueCalculation.leasePrincipal }}</el-descriptions-item>
          <el-descriptions-item label="利息(税前)合计">{{ revenueCalculation.leaseInterest }}</el-descriptions-item>
          <el-descriptions-item label="预计每期租金(税前)合计">{{
              revenueCalculation.leaseTotalAmount
            }}
          </el-descriptions-item>
          <el-descriptions-item label="项目收入"
          v-if="shouldDisplay('税前收益')">
            {{ revenueCalculation.projectIncome }}</el-descriptions-item>
          <el-descriptions-item label="利息支出"
          v-if="shouldDisplay('税前收益')">
            {{ revenueCalculation.interestExpense }}</el-descriptions-item>
          <el-descriptions-item label="IRR(含税)"
          v-if="shouldDisplay('税前收益')">
            {{ revenueCalculation.irrBeforeTax }}<span>%</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付的流转税"
          v-if="shouldDisplay('税后收益')">
            {{ revenueCalculation.turnoverTaxPaid }}</el-descriptions-item>
          <el-descriptions-item label="项目毛利润"
          v-if="shouldDisplay('税后收益')">
            {{ revenueCalculation.projectGrossProfit }}</el-descriptions-item>
          <el-descriptions-item label="IRR(税后)"
          v-if="shouldDisplay('税后收益')">
            {{ revenueCalculation.irrAfterTax }}<span>%</span>
          </el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>

    <el-divider></el-divider>
    <el-table v-loading="loading" :data="rentEstimationList" stripe highlight-current-row border>
      <el-table-column label="期次" prop="period" :show-overflow-tooltip="true" width="60"></el-table-column>
      <el-table-column label="还款日" prop="paymentDay" :show-overflow-tooltip="true" min-width="150"></el-table-column>
      <el-table-column label="预计每期租金(税前)" prop="preTaxRent" :show-overflow-tooltip="true"
                       min-width="150"></el-table-column>
      <el-table-column label="租赁本金" prop="leasingPrincipal" :show-overflow-tooltip="true"
                       min-width="150"></el-table-column>
      <el-table-column label="利息(税前)" prop="preTaxInterest" :show-overflow-tooltip="true"
                       min-width="150"></el-table-column>
      <el-table-column label="剩余本金" prop="remainingPrincipal" :show-overflow-tooltip="true"
                       min-width="150"></el-table-column>
      <el-table-column label="不规则还款本金录入" prop="irregularPrincipalInput" :show-overflow-tooltip="true"
                       min-width="150"></el-table-column>
      <el-table-column label="不规则还款利息录入" prop="irregularInterestInput" :show-overflow-tooltip="true"
                       min-width="150"></el-table-column>
    </el-table>


    <el-dialog title="下载租金计算表" :visible.sync="dialogVisible" width="30%" :before-close="handleCloseDialog"
               :close-on-click-modal="false">
      <el-form :model="downloadForm" ref="downloadForm" :rules="downloadRules" size="small" label-width="110px"
               label-position="right">
        <el-form-item label="客户名称" prop="customer" :rules="downloadRules.customer">
          <el-input v-model="downloadForm.customer" clearable style="width: 220px" placeholder="请输入">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <!-- <el-button size="mini" @click="dialogVisible = false">取 消</el-button> -->
                <el-button type="primary" size="mini" @click=handleConfirmDownload>确 定</el-button>
            </span>
    </el-dialog>

    <RatioCalculator ref="RatioCalculatorRef" @ok="RatioCalculatorOkFn"></RatioCalculator>
  </div>
</template>

<script>
import RatioCalculator from "./RatioCalculator"
import { getrentCalculate, rentCalculateDownload } from "@/api/processManage/approveForms";
import enumMixins from "../enumMixins";
import {blobValidate} from "@/utils/ruoyi";
import errorCode from "@/utils/errorCode";
import { saveAs } from 'file-saver'

export default {
  name: "Rent",
  dicts: ["sys_rent"],
  components: {RatioCalculator,},
  mixins: [enumMixins],
  props: {
    type: {
      type: String,
      required: true
    },
    // 商务条件
    businessForm: {
      leasingPrice: 0, // 合同价款
      leaseTermMonths: 24, // 融资期限(月)
      leasingMethod: 'DIRECT', // 租赁方式
      repaymentMethod: 'EQUAL_PRINCIPAL_AND_INTEREST', // 还款方式
      startDay: undefined, // 起始日
      breakPeriod: undefined, // 停歇期
      repaymentCycle: 'MONTHLY', // 还款周期
      gracePeriodMonths: 2, // 宽限期(月)
      marginDeductionMethod: undefined, // 保证金抵扣方式
      rentPaymentTiming: 'END', // 还租时点
      downPaymentPercentage: undefined, // 首付款比例
      marginPercentage: undefined, // 保证金比例
      feeRatePerYear: undefined, // 手续费率(年)
      feeTaxRate: 6, // 手续费税率
      nominalInterestRate: 10, // 名义收益率
      capitalCostRate: 7, // 资金成本率
      lessorOtherCosts: 0, // 出租人其他成本
      otherIncomeTaxIncluded: 0, // 其他收入(含税)
      downPayment: 0, // 首付款
      margin: 0, // 保证金
      fees: 0, // 手续费
      monthlyPayment: undefined, // 每日支付
    },
  },
  data() {
    return {
      dictSys_rent:[],
      // 遮罩层
      loading: false,

      // 表单校验
      rules: {
        leasingPrice: [ // 合同价款
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        leaseTermMonths: [ // 融资期限(月)
          {required: true, message: "不能为空", trigger: "blur"}
        ],
        repaymentMethod: [ // 还款方式
          {required: true, message: "不能为空", trigger: "change"}
        ],
        // startDay: [ // 起始日
        //     { required: true, message: "不能为空", trigger: "change" }
        // ],
        repaymentCycle: [ // 还款周期
          {required: true, message: "不能为空", trigger: "change"}
        ],
        rentPaymentTiming: [ // 还租时点
          {required: true, message: "不能为空", trigger: "change"}
        ],
        nominalInterestRate: [ // 名义收益率
          {required: true, message: "不能为空", trigger: "blur"},
          // { pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' },
          {
            pattern: /^(([1-9]?\d{0,1}(\.\d{1,2})?)|100|100\.(0){1,2})$/,
            message: '请输入0-100内的数字(最多2位小数)',
            trigger: 'blur'
          }
        ],
        capitalCostRate: [ // 资金成本率
          {required: true, message: "不能为空", trigger: "blur"},
          // { pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字且最多两位小数', trigger: 'blur' },
          {
            pattern: /^(([1-9]?\d{0,1}(\.\d{1,2})?)|100|100\.(0){1,2})$/,
            message: '请输入0-100内的数字(最多2位小数)',
            trigger: 'blur'
          }
        ],
        monthlyPayment: [ // 每月支付
          {required: true, message: "不能为空", trigger: "blur"}
        ],

      },

      // 租金表格数据
      rentEstimationList: [],

      // 租金收益测算
      revenueCalculation: {
        leasePrincipal: undefined,
        leaseInterest: undefined,
        leaseTotalAmount: undefined,
        projectIncome: undefined,
        interestExpense: undefined,
        irrBeforeTax: undefined,
        turnoverTaxPaid: undefined,
        projectGrossProfit: undefined,
        irrAfterTax: undefined,
        downPayment: undefined,
        downPaymentPercentage: undefined
      },

      // 下载弹窗
      dialogVisible: false,
      downloadForm: {
        customer: undefined,
      },
      // 下载校验
      downloadRules: {
        customer: [ // 用户名称
          {required: true, message: "不能为空", trigger: "blur"}
        ],
      },
    };
  },
  created() {
    this.dictSys_rent = this.dict.type.sys_rent
  },
  computed: {
    // 计算首付款比例(首付款/合同价款)
    downPaymentPercentage() {
      if (this.businessForm.downPayment && this.businessForm.leasingPrice) {
        return parseFloat(((this.businessForm.downPayment / this.businessForm.leasingPrice) * 100).toFixed(2))
      }
      return undefined
    },
    // 计算保证金比例(保证金/合同价款)
    marginPercentage() {
      if (this.businessForm.margin && this.businessForm.leasingPrice) {
        return parseFloat(((this.businessForm.margin / this.businessForm.leasingPrice) * 100).toFixed(2))
      }
      return undefined
    },
    // 计算手续费率(年)(手续费/合同价款)
    feeRatePerYear() {
      if (this.businessForm.fees && this.businessForm.leasingPrice) {
        return parseFloat(((this.businessForm.fees) / parseFloat(this.businessForm.leasingPrice) * 100).toFixed(2))
      }
      return undefined
    },
  },
  methods: {
    shouldDisplay(prop) {
      return this.dictSys_rent.some(item => item.label === prop && item.value === "0");
    },
    //计算比例
    ratioCalculatorFn(text){
      if(this.businessForm.leasingPrice == ''){
        this.$message.error('请先输入合同价款')
      }else{
        let params = {
          text:text,
          leasingPrice: this.businessForm.leasingPrice,
        }
        if(text=='SFK'){
          this.$set(params,'title','首付款比例计算')
        }
        if(text=='BZJ'){
          this.$set(params,'title','保证金比例计算')
        }
        this.$refs.RatioCalculatorRef.sync(params)

      }
    },
    RatioCalculatorOkFn(msg){
      if(msg.text=='SFK'){
        this.businessForm.downPayment = msg.money
      }
      if(msg.text=='BZJ'){
        this.businessForm.margin = msg.money
      }
    },
    handleRepaymentCycleChange() {
      if (this.businessForm.repaymentCycle !== 'MONTHLY') {
        this.businessForm.breakPeriod = undefined
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      let params = Object.assign({}, this.businessForm)
      params.type = 'common'
      params.startDay = this.formatDateChange(this.businessForm.startDay)
      params.downPaymentPercentage = this.businessForm.downPaymentPercentage / 100 // 首付款比例
      params.marginPercentage = this.businessForm.marginPercentage / 100 // 保证金比例
      params.feeRatePerYear = this.businessForm.feeRatePerYear / 100 // 手续费率(年)
      params.capitalCostRate = this.businessForm.capitalCostRate / 100 // 资金成本率
      params.nominalInterestRate = this.businessForm.nominalInterestRate / 100 // 名义收益率
      params.feeTaxRate = this.businessForm.feeTaxRate / 100 // 手续费税率
      if (this.type === 'reverse') {
        params.monthlyPayment = parseFloat(this.businessForm.monthlyPayment) // 每月支付
        params.reverseCalc = true
      }
      getrentCalculate(params).then(response => {
        this.revenueCalculation.leaseInterest = response.data.leaseInterest
        this.revenueCalculation.leasePrincipal = response.data.leasePrincipal
        this.revenueCalculation.leaseTotalAmount = response.data.leaseTotalAmount
        this.revenueCalculation.projectIncome = response.data.projectIncome
        this.revenueCalculation.interestExpense = response.data.interestExpense
        this.revenueCalculation.irrBeforeTax = (response.data.irrBeforeTax * 100).toFixed(2)
        this.revenueCalculation.turnoverTaxPaid = response.data.turnoverTaxPaid
        this.revenueCalculation.projectGrossProfit = response.data.projectGrossProfit
        this.revenueCalculation.irrAfterTax = (response.data.irrAfterTax * 100).toFixed(2)
        this.revenueCalculation.downPayment = response.data.downPayment
        this.revenueCalculation.downPaymentPercentage = response.data.downPaymentPercentage
        this.rentEstimationList = response.data.rentEstimationList
        this.loading = false
      });
    },

    handleCount() {
      this.$refs["businessForm"].validate(valid => {
        if (valid) {
          this.getList();
        }
      });

    },

    handleClear() {
      this.resetForm("businessForm");
      this.businessForm.leasingPrice =''
    },

    // 下载
    handleDownload() {
      this.downloadForm.customer = undefined
      this.dialogVisible = true
    },

    // 关闭下载弹窗
    handleCloseDialog() {
      this.dialogVisible = false
      this.resetForm("downloadForm");
    },

    handleConfirmDownload() {
      this.$refs["businessForm"].validate(valid => {
        if (valid) {
          this.dialogVisible = false
          let params = Object.assign({}, this.businessForm)
          params.startDay = this.formatDateChange(this.businessForm.startDay)
          params.capitalCostRate = this.businessForm.capitalCostRate / 100 // 资金成本率
          params.nominalInterestRate = this.businessForm.nominalInterestRate / 100 // 名义收益率
          params.feeTaxRate = this.businessForm.feeTaxRate / 100 // 手续费税率
          params.customer = "" // 客户名称
          params.type = "common"
          params.identity = 2
          if (this.type === 'reverse') {
            params.monthlyPayment = parseFloat(this.businessForm.monthlyPayment) // 每月支付
            params.reverseCalc = true
          }
          rentCalculateDownload(params).then(async(data) => {
            const isBlob = blobValidate(data)
            if (isBlob) {
              const blob = new Blob([data])
              let filename = decodeURI(data.filename)
              saveAs(blob, filename)
            } else {
              const resText = await data.text()
              const rspObj = JSON.parse(resText)
              const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
              this.$message.error(errMsg)
            }
          }).catch((r) => {
            this.$message.error('下载文件出现错误，请联系管理员！')
          })
        }
      });
    },
  }
};
</script>
